#include "VideoConvertX.h"
namespace FFMPEGCPP
{

CVideoConvert::CVideoConvert(void)
{
	m_pSwsContext = 0;

	m_srcW = 0;
	m_srcH = 0;
	m_srcFormat = AV_PIX_FMT_NONE;
	m_dstW  =0;
	m_dstH = 0;
	m_dstFormat = AV_PIX_FMT_NONE;
	m_flags = 0;
}

CVideoConvert::~CVideoConvert(void)
{
	UnInit();
}


bool CVideoConvert::Init( int srcW, int srcH, enum AVPixelFormat srcFormat,int dstW, int dstH, enum AVPixelFormat dstFormat,int flags )
{

	if( srcW == m_srcW &&
	srcH == m_srcH &&
	srcFormat == m_srcFormat &&
	dstW == m_dstW &&
	dstH == m_dstH &&
	dstFormat == m_dstFormat &&
	flags == flags )return true;


	m_srcW = srcW;
	m_srcH = srcH;
	m_srcFormat = srcFormat;
	m_dstW  =dstW;
	m_dstH = dstH;
	m_dstFormat = dstFormat;
	m_flags = flags;



	UnInit();
	m_pSwsContext = sws_getContext( srcW,srcH,srcFormat,dstW,dstH,dstFormat,flags,0,0,0 );
	return m_pSwsContext != 0;
}



void CVideoConvert::UnInit()
{
	if(m_pSwsContext)sws_freeContext(m_pSwsContext);
	m_pSwsContext=  0;
}

bool CVideoConvert::ReInit( const CAVPicture* picture_src,const CAVPicture* picture_dst,int flags /*= SWS_FAST_BILINEAR */ )
{

	if( 0 == picture_dst || 0 == picture_dst )return false;

	return Init( picture_src->GetWidth(),picture_src->GetHeight(),picture_src->GetFormat(),
		picture_dst->GetWidth(),picture_dst->GetHeight(),picture_dst->GetFormat(),
		flags );
}
bool CVideoConvert::Convert( const uint8_t *const srcSlice[],const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[] )
{
	if( 0 == m_pSwsContext )return false;

	return 0 == sws_scale( m_pSwsContext,srcSlice,srcStride,srcSliceY,srcSliceH,dst,dstStride );
}
bool CVideoConvert::Convert( const CAVPicture* picture_src,CAVPicture* picture_dst )
{
	if( 0 == picture_dst || 0 == picture_dst )return false;

	picture_dst->SetPTS(picture_src->GetPTS());
	picture_dst->SetTimeBase(picture_src->GetTimeBase());
	return Convert( picture_src->GetPicture()->data,picture_src->GetPicture()->linesize,
		0,picture_src->GetHeight(),
		picture_dst->GetPicture()->data,picture_dst->GetPicture()->linesize);
}

}